class Subject {//被观察者
    constructor(name) {
        this.name = name
        this.observers = [] //观察者不止一个
        this.state = '状态1'
    }
    attach(observer) { //被观察者要将观察者纳入里面
        this.observers.push(observer)
    }
    changeState(newstate) {//更改被观察者的状态
        this.state = newstate
        this.observers.forEach(O => O.update(newstate))
    }
}
class Observer {
    constructor(name) {
        this.name = name
    }
    update(newstate) {//通知所有观察者你，被观察者状态已改变
        console.log(this.name, newstate);
    }
}
let sub1 = new Subject('被观察者')
let ob1 = new Observer('观察者1')
let ob2 = new Observer('观察者2')
sub1.attach(ob1)
sub1.attach(ob2)
sub1.changeState('状态2')